package utils;

public class BinarySearch {

    /**
     * 返回元素位置/插入位置（前提数组有序）
     * @param nums
     * @param target
     * @return
     */
    public static int searchInsert(int[] nums, int target) {
        int left = 0, right = nums.length - 1, mid;
        while(left <= right) {
            mid = left + (right - left) / 2;
            if (nums[mid] == target)
                return mid;
            else if (nums[mid] < target)
                left = mid + 1;
            else
                right = mid - 1;
        }
        // 未找到，返回插入位置
        return left;
    }

    // 另一种写法，更好，无序递增，只需非递减即可
    public int searchInsert_(int[] nums, int target) {
        int low = 0, high = nums.length - 1;
        while(low <= high) {
            int mid = (low + high) / 2;
            if (nums[mid] < target) {
                low = mid + 1;
            }
            else {
                high = mid - 1;
            }
        }
        return low;
    }

    /**
     * 返回target最左面的位置（前提数组有序）
     * @param nums
     * @param target
     * @return
     */
    public static int searchLeft(int[] nums, int target) {
        int left = 0, right = nums.length - 1, mid, ans = -1;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                ans = mid;
                right = mid - 1;
            }
            else if (nums[mid] < target) {
                left = mid + 1;
            }
            else {
                right = mid - 1;
            }
        }

        return ans;
    }

    public static void main(String[] args) {
        BinarySearch binarySearch = new BinarySearch();
        System.out.println(binarySearch.searchInsert_(new int[]{1,2,2,2,4,4,4,5}, 3));
    }
}
